<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import myAxios from "../../../plugins/myAxios.js";

// 列表数据
const tableData = ref([])
// 添加分页参数
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})
// 对话框显示控制
const dialogVisible = ref(false)
// 表单数据
const form = ref({
  id:-1,
  title: '',
  content: '',
  videoUrl: '',
  videoFile: null
})
// 是否为编辑模式
const isEdit = ref(false)
// 视频预览对话框控制
const videoDialogVisible = ref(false)
const currentVideo = ref('')

// 获取列表数据
const getList = async () => {
  try {
    const res = await myAxios.get('/admin/testguide/page', {
      current: pagination.value.current,
      pageSize: pagination.value.pageSize
    })
    tableData.value = res.records
    pagination.value.total = res.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}

// 添加分页变化处理方法
const handlePageChange = (page) => {
  pagination.value.current = page
  getList()
}

const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.current = 1
  getList()
}

// 处理视频文件上传
const handleVideoUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 验证文件类型
    if (!file.type.startsWith('video/')) {
      ElMessage.error('请上传视频文件')
      return
    }
    // 验证文件大小（这里设置最大100MB）
    if (file.size > 100 * 1024 * 1024) {
      ElMessage.error('视频文件大小不能超过100MB')
      return
    }
    form.value.videoFile = file
    // 创建本地预览URL
    form.value.videoUrl = URL.createObjectURL(file)
  }
}

// 修改提交表单方法
const handleSubmit = async () => {
  try {
    if (!form.value.videoFile && !form.value.videoUrl) {
      ElMessage.error('请上传视频文件')
      return
    }

    // 创建 FormData 对象
    const formData = new FormData()
    formData.append('title', form.value.title)
    formData.append('content', form.value.content)
    if (form.value.videoFile) {
      formData.append('video', form.value.videoFile)
    }else{
      formData.append('video', null)
    }
    if(isEdit.value){
      formData.append('id', form.value.id)
    }

    // 发送 multipart/form-data 请求
    await myAxios.post('/admin/testguide/' + (isEdit.value ? 'update' : 'add'), formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
    dialogVisible.value = false
    getList()

    // 清理本地预览URL
    if (form.value.videoFile) {
      URL.revokeObjectURL(form.value.videoUrl)
    }
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
  }
}

// 对话框关闭时清理
const handleDialogClose = () => {
  if (form.value.videoFile) {
    URL.revokeObjectURL(form.value.videoUrl)
  }
  form.value = {
    id:-1,
    itemName: '',
    trainingContent: '',
    videoUrl: '',
    videoFile: null
  }
}

// 修改预览视频方法
const previewVideo = (url) => {
  // // 检查是否为本地文件路径
  // if (url.startsWith('file://') || url.startsWith('/')) {
  //   ElMessage.warning('无法直接预览本地视频文件')
  //   return
  // }
  console.log(url)
  currentVideo.value = url
  videoDialogVisible.value = true
}

// 删除训练指导
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该训练指导吗？', '提示', {
      type: 'warning'
    })

    // TODO: 替换为实际的删除API
    await myAxios.post(`/admin/testguide/delete/${row.id}`)

    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="training-content">
    <div class="header">
      <h2>测试指南管理</h2>
      <el-button type="primary" @click="dialogVisible = true; isEdit = false">添加训练指导</el-button>
    </div>

    <el-table :data="tableData" border>
      <el-table-column prop="title" label="指南名称" />
      <el-table-column prop="content" label="指南内容" show-overflow-tooltip />
      <el-table-column prop="videoUrl" label="指南视频预览" show-overflow-tooltip>
        <template #default="scope">
          <el-button
              type="primary"
              link
              @click="previewVideo(scope.row.videoUrl)"
              :disabled="!scope.row.videoUrl || scope.row.videoUrl.startsWith('file://')"
          >
            预览视频
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="publisherName" label="发布人" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="primary" link @click="
            isEdit = true;
            form = { ...scope.row };
            dialogVisible = true;
          ">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        layout="total, sizes, prev, pager, next"
        class="pagination"
    />

    <el-dialog
        :title="isEdit ? '编辑训练指导' : '添加训练指导'"
        v-model="dialogVisible"
        width="500px"
        @closed="handleDialogClose"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="指南名称">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="指南内容">
          <el-input v-model="form.content" type="textarea" rows="4" />
        </el-form-item>
        <el-form-item label="上传视频">
          <input
              type="file"
              accept="video/*"
              @change="handleVideoUpload"
              style="margin-bottom: 10px"
          >
          <!-- 视频预览 -->
          <div v-if="form.videoUrl" class="video-preview">
            <video
                :src="form.videoUrl"
                controls
                style="width: 100%; max-height: 200px"
            >
              您的浏览器不支持 video 标签
            </video>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
        title="视频预览"
        v-model="videoDialogVisible"
        width="800px"
        destroy-on-close
    >
      <div class="video-container">
        <video
            v-if="currentVideo"
            :src="currentVideo"
            controls
            class="preview-video"
        >
          您的浏览器不支持 video 标签
        </video>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.training-content {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.video-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-video {
  width: 100%;
  max-height: 450px;
  object-fit: contain;
}

.video-preview {
  margin-top: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>